﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BTKERP.Common.DataHelper;
using System.Data;
using System.Data.SqlClient;

namespace BTKERP.DAL.DataAccess
{
    public partial class DBContext
    {
        //private static ISysLog log = SysLog.GetLogger("DBContext");
        public bool ExecuteCommand(ExSQLCommand command)
        {
            bool result;

            Connection connectionInfo = ConnectionInfo;
            try
            {
                command.Connection = connectionInfo.ConnectionInfo;
                connectionInfo.ConnectionInfo.Open();
                command.cmd.ExecuteNonQuery();
                result = true; 
            }
            catch (Exception e)
            {
                //log.Exception(e);
                result = false;
            }
            finally
            {
                connectionInfo.Close();
                ConnectionInfo = connectionInfo;
            }
            return result;
        }

        public DataSet GetDataSet(ExSQLCommand command)
        {
            DataSet ds = new DataSet();
            Connection conn = ConnectionInfo;
            try
            {
                command.Connection = conn.ConnectionInfo;
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(command.cmd);
                da.Fill(ds);
            }
            catch (Exception e)
            {
                //log.Exception(e);
                //log.Info("Current Connection String::" + conn.ConnectionString);
            }
            finally
            {
                conn.Close();
                ConnectionInfo = conn;
            }
            return ds;
        }

        public DataTable GetDataTable(ExSQLCommand command)
        {
            DataSet ds = GetDataSet(command);
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return new DataTable();
        }

        public List<T> GetEntityList<T>(ExSQLCommand command) where T : new()
        {
            DataTable dt = GetDataTable(command);
            return EntityHelper.EncapsulateObj<T>(dt);
        }

        public T GetSingleEntity<T>(ExSQLCommand command) where T : new()
        {
            DataTable dt = GetDataTable(command);
            if (dt.Rows.Count == 0)
            {
                return default(T);
            }


            return EntityHelper.EncapsulateObj<T>(dt.Rows[0]);
        }

        public string GetSingleValue(ExSQLCommand command)
        {
            DataTable dt = GetDataTable(command);
            if (dt.Rows.Count == 0)
            {
                return string.Empty;
            }

            return dt.Rows[0][0].ToString();
        }
    }
}
